<?php
declare (strict_types=1);

namespace app\service;


use think\facade\Db;
use app\model\BaseModel;
use app\util\TreeUtil;
/**
 * 管理员
 * Class SysUserService
 * @package app\service
 */
class SysUserUpdateService
{

    /**
     * 管理员列表
     * @param array $param 参数数组
     * @return json
     */
    public static function getSysUserList($param)
    {

        $model = Db::table('sys_user')->alias('sy');
        if (!empty($param['condition'])) {
            $where = 'sy.account like "%' . $param['condition'] . '%" or sy.user_name like "%' . $param['condition'] . '%" or sy.phone like "%' . $param['condition'] . '%"';
            $model->where($where);
        }
        $res = $model->leftJoin('sys_dept sd', 'sy.dept_id = sd.id')
            ->where('sy.is_del', 0)
            ->field('sy.id,sy.user_name as userName,sy.account,sy.sex,sy.phone,sy.id_card as idCard,sy.dept_id as deptId,sd.dept_name as deptName,sy.position,sy.email,sy.enable')
            ->paginate(['page' => $param['page'], 'list_rows' => $param['pageSize']])->toArray();
        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        $list = ['total' => $res['total'], 'currentPage' => $res['current_page'], 'lastPage' => $res['last_page'], 'data' => $res['data']];
        return json_ok($list, 0);

    }

    /**
     * 管理员新增
     * @param array $param 参数数组
     * @return json
     */
    public static function sysUserAdd($param)
    {

        $isAccount = Db::table('sys_user')->alias('sy')->where('account', $param['account'])->find();
        if ($isAccount && $isAccount['is_del'] == 0) {
            return json_error(100, '账户已存在');
        }

        BaseModel::beginTrans();
        try {
            if ($isAccount && $isAccount['is_del'] == 1) {
                Db::table('sys_user')->alias('sy')->where('account', $param['account'])->where('is_del', 1)->delete();
            }

            $data = [];
            $data['account'] = $param['account'];
            $data['user_name'] = $param['userName'];
            $data['id_card'] = $param['idCard'];
            $data['dept_id'] = $param['deptId'];
            $data['enable'] = $param['enable'];
            $data['password'] = $param['password'] ? encrypt_pass($param['password']) : encrypt_pass('123456');
            $data['sex'] = $param['sex'];
            $data['wei_xin'] = $param['weiXin'];
            $data['position'] = $param['position'];
            $data['birth_day'] = $param['birth_day'];
            $data['wei_bo'] = $param['weiBo'];
            $data['phone'] = $param['phone'];
            $data['qq'] = $param['qq'];
            $data['email'] = $param['email'];
            Db::name('sys_user')->save($data);

            if ($param['roleId']) {
                $userId = Db::name('sys_user')->max('id');
                foreach ($param['roleId'] as $key => $value) {
                    $data = [];
                    $data['user_id'] = $userId;
                    $data['role_id'] = $value;
                    $data['enable'] = 1;
                    $data['create_by'] = 1;
                    $data['update_by'] = 1;
                    Db::name('sys_user_role')->save($data);
                }
            }
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 200);


    }

    /**
     * 管理员编辑
     * @param array $param 参数数组
     * @return json
     */
    public static function sysUserEdit($param)
    {


        $isSysUserId = Db::table('sys_user')->alias('sy')->where('id', $param['sysUserId'])->find();
        if (empty($isSysUserId)) {
            return json_error(100, '记录不存在');
        }
        if($param['nowUserId'] != 1){
            if($param['sysUserId'] == $param['nowUserId']){
                if($isSysUserId['enable'] !=$param['enable']){
                    return json_error(100, '普通账号无权对自身封禁状态做更改');
                }
            }
            if($param['sysUserId'] ==1){
                return json_error(100, '无权对超级管理员进行操作');
            }
        }
        if($isSysUserId['account'] != $param['account']){
            return json_error(100, '登录账号无法修改，请重新提交');
        }

        BaseModel::beginTrans();
        try {
            $data = [];
//            $data['account'] = $param['account'];
            $data['user_name'] = $param['userName'];
            $data['id_card'] = $param['idCard'];
            $data['dept_id'] = $param['deptId'];
            $data['enable'] = $param['enable'];
            if (!empty($param['password'])) {
                $data['password'] = encrypt_pass($param['password']);
            }
            $data['sex'] = $param['sex'];
            $data['wei_xin'] = $param['weiXin'];
            $data['position'] = $param['position'];
            $data['birth_day'] = $param['birth_day'];
            $data['wei_bo'] = $param['weiBo'];
            $data['phone'] = $param['phone'];
            $data['qq'] = $param['qq'];
            $data['email'] = $param['email'];
            Db::name('sys_user')->where('id', $param['sysUserId'])->where('is_del', 0)->data($data)->update();

            //处理用户角色增删改查情况
            foreach ($param['roleId'] as $key => $value) {
                $record = Db::name('sys_user_role')->where('user_id', $param['sysUserId'])->where('role_id', $value)->find();
                if ($record) {
                    if ($record['is_del'] == 1) {
                        Db::name('sys_user_role')->where('user_id', $param['sysUserId'])->where('role_id', $value)->where('is_del', 1)->update(['is_del' => 0]);
                    }
                } else {
                    $data = [];
                    $data['user_id'] = $param['sysUserId'];
                    $data['role_id'] = $value;
                    $data['enable'] = 1;
                    $data['create_by'] = 1;
                    $data['update_by'] = 1;
                    Db::name('sys_user_role')->save($data);
                }
            }

            Db::name('sys_user_role')->where('user_id', $param['sysUserId'])->where('is_del', 0)->where('role_id', 'not in', $param['roleId'])->update(['is_del' => 1]);
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 200);


    }

    /**
     * 管理员详情
     * @param string $sysUserId 账户ID
     * @return json
     */
    public static function sysUserDetails($sysUserId)
    {

        $res = Db::table('sys_user')->alias('sy')
            ->field('sy.id as sysUserId,sy.account as account,sy.user_name as userName,sy.id_card as idCard,sy.dept_id as deptId,sy.enable as enable,sy.sex as sex,sy.wei_xin as weiXin,sy.position as position,sy.birth_day as birthDay,sy.wei_bo as weiBo,sy.qq as qq,sy.phone as phone,sy.email as email')
            ->where('id', $sysUserId)
            ->where('is_del', 0)
            ->find();
        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        $res['deptName'] = Db::table('sys_dept')->where('id', $res['deptId'])->value('dept_name');
        return json_ok($res, 200);

    }

    /**
     * 管理员删除
     * @param string $sysUserId 账户ID
     * @return json
     */
    public static function sysUserDelete($sysUserId)
    {

        BaseModel::beginTrans();
        try {
            if (strpos($sysUserId, ',') !== false) {

                Db::table('sys_user')->where('id', 'in', $sysUserId)->update(['is_del' => '1']);
            } else {
                Db::table('sys_user')->where('id', $sysUserId)->update(['is_del' => '1']);
            }
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 200);

    }

    /**
     * 部门列表
     * @param
     * @return json
     */
    public static function getDeptNameList()
    {

        $res = Db::table('sys_dept')->where('is_del',0)->field('id,parent_id as parentId,dept_name as title')->select()->toArray();
        $r =  TreeUtil::list_to_tree($res, 0, 'id', 'parentId', $child = 'children');
        return json_ok($r , 200);

    }

    /**
     * 根据部门ID获取角色列表
     * @param
     * @return json
     */
    public static function getRoleByDeptId($deptId)
    {

        $res = Db::table('sys_role')->field('id,role_name as roleName')->where('enable',1)->where('is_del',0)->where('dept_id', $deptId)->select();
        if (empty($res)) {
            return json_error(100, '记录不存在');
        }
        return json_ok($res, 200);

    }

    /**
     * 根据用户ID获取角色
     * @param
     * @return json
     */
    public static function getRoleByUserId($userId)
    {

        $res = Db::table('sys_user_role')->field('role_id as roleId')->where('enable',1)->where('is_del',0)->where('user_id', $userId)->where('is_del', 0)->select();
        if (empty($res)) {
            return json_error(100, '记录不存在');
        }
        return json_ok($res, 200);

    }
}
